/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 */
define(['N/record', 'N/search', 'N/ui/dialog', 'N/log'], function (record, search, dialog, log) {
    var woId, wo, results;

    function pageInit(context) {
        if (context.currentRecord.getValue('custpage_refresh_status')) {
            setTimeout(function () {
                window.history.back(-1)
            }, 3000); //返回
        }
    }

    function validateField(context) {
        if (context.fieldId === 'custpage_process_barcodescan') {  //工序号
            var operationsequence = context.currentRecord.getValue('custpage_process_barcodescan');
            if (isNaN(operationsequence)){
                dialog.alert({title: "提示", message: "您只可在此字段内输入数字!"});
                context.currentRecord.setValue('custpage_process_barcodescan','');
                return false;
            }
            if (operationsequence === '') {
                context.currentRecord.setValue('custpage_operationsequence', '');
                context.currentRecord.setValue('custpage_operationname', '');
                context.currentRecord.setValue('custpage_completedquantity', '');
                context.currentRecord.setValue('custpage_reportworkquantity', '');
                return true;
            }
            var woBarcode = context.currentRecord.getValue('custpage_wo_barcodescan');
            if (woBarcode.length <= 0) {
                dialog.alert({title: "提示", message: "请扫描工单条码!"});
                context.currentRecord.setValue('custpage_process_barcodescan', '');
                return false;
            }
            if (operationsequence > results.length) {
                dialog.alert({title: "提示", message: "请扫描正确的工序号:1-" + results.length});
                context.currentRecord.setValue('custpage_process_barcodescan', '');
                context.currentRecord.setValue('custpage_operationsequence', '');
                context.currentRecord.setValue('custpage_operationname', '');
                context.currentRecord.setValue('custpage_completedquantity', '');
                context.currentRecord.setValue('custpage_reportworkquantity', '');
                return false;
            }
            var manufacturingcosttemplateId = results[Number(operationsequence) - 1].getValue('manufacturingcosttemplate');
            var fieldLookUp = search.lookupFields({
                type: 'manufacturingcosttemplate',
                id: manufacturingcosttemplateId,
                columns: ['custrecord_processtype']
            });
            var processTypeId = fieldLookUp.custrecord_processtype[0].value;
            if (processTypeId === '1' || processTypeId === '2' || processTypeId === '3') {//外协工序
                dialog.alert({title: "提示", message: "委外工序无法扫码完工!"});
                context.currentRecord.setValue('custpage_process_barcodescan', '');
                context.currentRecord.setValue('custpage_operationsequence', '');
                context.currentRecord.setValue('custpage_operationname', '');
                context.currentRecord.setValue('custpage_completedquantity', '');
                context.currentRecord.setValue('custpage_reportworkquantity', '');
                return false;
            }
            var arr = woBarcode.split("/");
            var wocSearchResults = search.create({
                type: 'workordercompletion',
                columns: [],
                filters: [['createdfrom', 'is', woId],
                    'and', ['custbody_wo_processnum', 'equalto', Number(operationsequence)],
                    'and', ['custbody_packageno', 'is', Number(arr[1])]]//包号是 free-text类型
            }).run().getRange(0, 1);
            if (wocSearchResults.length > 0) {
                dialog.alert({title: "提示", message: "此工序对应包号已完成报工,请勿重复报工!"});
                context.currentRecord.setValue('custpage_process_barcodescan', '');
                context.currentRecord.setValue('custpage_operationsequence', '');
                context.currentRecord.setValue('custpage_operationname', '');
                context.currentRecord.setValue('custpage_completedquantity', '');
                context.currentRecord.setValue('custpage_reportworkquantity', '');
                return false;
            }
            //非第一道工序
            if (Number(operationsequence) != 1){
                //获得上道工序完工数量
                var predecessorCompletedquantity = Number(results[Number(operationsequence) - 2].getValue('completedquantity'));
                //查找当前工序报工数量
                var currentReportquantity = 0;
                search.create({
                    type: 'workordercompletion',
                    columns: ['custbody_reportwork_qty'],
                    filters: [['createdfrom', 'is', woId], 'and', ['mainline', 'is', 'T'], 'and', ['custbody_wo_processnum', 'equalto', Number(operationsequence)]]
                }).run().each(function (result) {
                    currentReportquantity += Number(result.getValue('custbody_reportwork_qty'));
                    return true;
                });
                if (predecessorCompletedquantity <= currentReportquantity){
                    dialog.alert({title: "提示", message: "无法完工!上道工序总完工数量:"+predecessorCompletedquantity+",本道工序总报工数量:"+currentReportquantity});
                    context.currentRecord.setValue('custpage_process_barcodescan', '');
                    return false;
                }
            }


        }
        if (context.fieldId === 'custpage_reportworkquantity') { //报工数量
            var reportworkquantity = context.currentRecord.getValue('custpage_reportworkquantity');//报工数量
            if (reportworkquantity == ''){
                return true;
            }
            var packagenumberquantity = context.currentRecord.getValue('custpage_packagenumberquantity');//包号对应数量
            var completedquantity = context.currentRecord.getValue('custpage_completedquantity');//已完成数量
            if (reportworkquantity > packagenumberquantity) {
                dialog.alert({title: "提示", message: "报工数量不能大于包号对应的数量:" + packagenumberquantity});
                context.currentRecord.setValue('custpage_reportworkquantity', packagenumberquantity);
                return false;
            }
            if (reportworkquantity < completedquantity) {
                dialog.alert({title: "提示", message: "报工数量不能小于已完成数量"});
                context.currentRecord.setValue('custpage_reportworkquantity', completedquantity);
                return false;
            }
        }
        if (context.fieldId === 'custpage_completedquantity') {//完工数量
            var reportworkquantity = context.currentRecord.getValue('custpage_reportworkquantity');//报工数量
            var completedquantity = context.currentRecord.getValue('custpage_completedquantity'); //已完成数量
            if (completedquantity == ''){
                return true;
            }
            if (completedquantity > reportworkquantity) {
                dialog.alert({title: "提示", message: "已完成数量不能大于报工数量"});
                context.currentRecord.setValue('custpage_completedquantity', reportworkquantity);
                return false;
            }
        }
        if (context.fieldId === 'custpage_defectivequantity' || context.fieldId === 'custpage_crapquantity') {
            if (context.currentRecord.getValue(context.fieldId) === '') {
                return true;
            }
            var reportworkquantity = context.currentRecord.getValue('custpage_reportworkquantity'); //报工数量
            var completedQuantity = context.currentRecord.getValue('custpage_completedquantity');//完工数量
            var defectiveQuantity = context.currentRecord.getValue('custpage_defectivequantity');//次品数量
            var crapQuantity = context.currentRecord.getValue('custpage_crapquantity');//废品数量
            var quantity = completedQuantity + defectiveQuantity + crapQuantity;
            if (quantity > reportworkquantity) {
                dialog.alert({title: "提示", message: "[完工数量、次品数量、废品数量]总和不能大于报工数量!"});
                context.currentRecord.setValue({fieldId: context.fieldId, value: '', ignoreFieldChange: true});
                return false;
            } else {
                context.currentRecord.setValue('custpage_reportworkquantity', quantity);
            }
        }
        return true;
    }

    function fieldChanged(context) {
        try {
            if (context.fieldId === 'custpage_wo_barcodescan') {
                var woBarcode = context.currentRecord.getValue('custpage_wo_barcodescan');
                if (woBarcode.length > 0) {
                    if (woBarcode.indexOf("/") === -1) {
                        dialog.alert({title: "提示", message: "请扫描正确的工单标签"});
                        clearAll(context);
                    } else {
                        var arr = woBarcode.split("/");
                        var woTruedocnumber = arr[0];  //工单编号
                        if (isNaN(arr[1])){
                            dialog.alert({title: "提示", message: "请扫描正确的工单标签:包号无效"});
                            clearAll(context);
                        }
                        var woSearchResults = search.create({
                            type: 'workorder',
                            columns: ['custbody_package'],
                            filters: [["truedocnumber", "is", woTruedocnumber]]
                        }).run().getRange(0, 1);
                        if (woSearchResults.length > 0) {
                            woId = woSearchResults[0].id;
                            var maxPackageNum = woSearchResults[0].getValue('custbody_package');
                            if (arr[1] > maxPackageNum){
                                dialog.alert({title: "提示", message: "包号最大为"+maxPackageNum+"，请重新扫码"});
                                clearAll(context);
                                return ;
                            }
                            results = search.create({
                                type: 'manufacturingoperationtask',
                                columns: ['name', 'manufacturingcosttemplate','completedquantity'],
                                filters: [['workorder', 'is', woId]]
                            }).run().getRange(0, 100);
                            context.currentRecord.setValue('custpage_wo_num', woId);  //设置工单编号
                            context.currentRecord.setValue('custpage_packagenumber', arr[1]);  //设置包号
                            wo = record.load({type: 'workorder', id: woId, isDynamic: true});
                            var assemblyitemId = wo.getValue('assemblyitem');
                            var lookupFields = search.lookupFields({
                                type: search.Type.ASSEMBLY_ITEM,
                                id: assemblyitemId,
                                columns: ['itemid', 'displayname', 'custitem_color', 'custitem_size', 'custitem_color_number']
                            });
                            context.currentRecord.setValue('custpage_salesorder', wo.getText('custbody_contractno'));  //设置合同编号
                            context.currentRecord.setValue('custpage_assemblyitem', lookupFields.itemid);//设置产品编号
                            context.currentRecord.setValue('custpage_itemname', lookupFields.displayname);//设置产品名称
                            context.currentRecord.setValue('custpage_itemsize', lookupFields.custitem_size);//设置尺寸
                            context.currentRecord.setValue('custpage_itemcolor', lookupFields.custitem_color[0].text);//设置颜色
                            context.currentRecord.setValue('custpage_itemcolornumber', lookupFields.custitem_color_number[0].text);//设置色号
                            context.currentRecord.setValue('custpage_perquantity', wo.getValue('custbody_piecepackage'));//设置 件/包
                            context.currentRecord.setValue('custpage_packagecount', wo.getValue('custbody_package'));  //设置 包数
                            context.currentRecord.setValue('custpage_realperquantity', wo.getValue('quantity'));//设置 数量
                        } else {
                            dialog.alert({title: "提示", message: "请扫描正确的工单标签"});
                            clearAll(context);
                            return ;
                        }
                        // 设置每包对应的数量（已完成数量）packageNumber包号 packageCount 包数
                        var packageCount = wo.getValue('custbody_package');
                        var packageNumber = arr[1];
                        var packageNumberQuantity;
                        if (packageNumber < packageCount) {
                            packageNumberQuantity = wo.getValue('custbody_piecepackage');
                            context.currentRecord.setValue('custpage_packagenumberquantity', packageNumberQuantity);//件/包
                        } else {
                            packageNumberQuantity = wo.getValue('quantity') - (packageNumber - 1) * wo.getValue('custbody_piecepackage');
                            context.currentRecord.setValue('custpage_packagenumberquantity', packageNumberQuantity);
                        }
                    }
                }
            }
            if (context.fieldId === 'custpage_process_barcodescan') {
                var operationsequence = context.currentRecord.getValue('custpage_process_barcodescan');
                if (operationsequence !== '') {
                    context.currentRecord.setValue("custpage_operationsequence", operationsequence);//设置工序号
                    var operationname = results[Number(operationsequence) - 1].getValue('name');
                    context.currentRecord.setValue("custpage_operationname", operationname);//设置工序名称
                    var packageNumberQuantity = context.currentRecord.getValue('custpage_packagenumberquantity');  //每包对应的数量
                    context.currentRecord.setValue('custpage_reportworkquantity', packageNumberQuantity);//设置报工数量
                    context.currentRecord.setValue('custpage_completedquantity', packageNumberQuantity);//设置已完成数量
                }
            }
            if (context.fieldId === 'custpage_employee') {
                var count = context.currentRecord.getLineCount("custpage_completedetails");
                context.currentRecord.selectLine('custpage_completedetails', context.line);
                var curEmployee = context.currentRecord.getCurrentSublistText('custpage_completedetails', 'custpage_employee');
                var index;
                if (count > 0) {
                    for (var i = 0; i < count; i++) {
                        var employee = context.currentRecord.getSublistText('custpage_completedetails', 'custpage_employee', i);
                        if (curEmployee === employee) {
                            dialog.alert({title: "提示", message: "相同员工，重复报工"});
                            index = i;
                            context.currentRecord.cancelLine('custpage_completedetails');
                            break;
                        }
                    }
                }
                var quantity = context.currentRecord.getValue('custpage_reportworkquantity');
                var averageQuantity;
                if (typeof (index) == 'number' && index >= 0) {
                } else {
                    context.currentRecord.commitLine('custpage_completedetails');
                    count++;
                }
                averageQuantity = (quantity / count).toFixed(2);
                if (count > 0) {
                    for (var i = 0; i < count; i++) {
                        context.currentRecord.selectLine('custpage_completedetails', i);
                        context.currentRecord.setCurrentSublistValue('custpage_completedetails', 'custpage_completedcount', averageQuantity);
                    }
                }
                if (typeof (index) == 'number' && index >= 0) {
                    context.currentRecord.selectLine('custpage_completedetails', index);
                }
            }
        } catch (e) {
        }
    }

    function saveRecord(context) {
        if (context.currentRecord.getLineCount('custpage_completedetails') <= 0) {
            alert('请填充员工报工列表');
            return false;
        }

        // var reportworkquantity = context.currentRecord.getValue('custpage_reportworkquantity');
        // //windy   报工数量不能大于(上道工序总完成数量 -  本道工序总报工数量)
        // var startoperationText = context.currentRecord.getValue('custpage_process_barcodescan');
        // if (Number(startoperationText) > 1) {
        //     var subtractQuantity = getSubtractQuantity(startoperationText, reportworkquantity);
        //     if (reportworkquantity > subtractQuantity) {
        //         return false;
        //     }
        // }

        // //创建完工工单
        // var woc = record.transform({
        //     fromType: 'workorder',
        //     fromId: woId,
        //     toType: 'workordercompletion',
        //     isDynamic: true
        // });
        // woc.setValue('isbackflush', false); //设置为正向排程
        // woc.setValue('custbody_packageno', context.currentRecord.getValue('custpage_packagenumber')); //包号
        // woc.setValue("custbody_actual_issue_location", wo.getValue('location'));  //实际完工地点
        // woc.setValue("custbody_bin", 3);//实际完工库位
        // woc.setText("startoperation", Number(context.currentRecord.getValue('custpage_operationsequence'))); //开始操作
        // woc.setText("endoperation", Number(context.currentRecord.getValue('custpage_operationsequence')));   //结束操作
        // woc.setValue("completedquantity", context.currentRecord.getValue('custpage_completedquantity'));  //已完成数量
        // woc.setValue("custbody_reportwork_qty", context.currentRecord.getValue('custpage_reportworkquantity'));//报工数量
        // woc.setValue("custbody_defectivequantity", context.currentRecord.getValue('custpage_defectivequantity')); //次品数量
        // woc.setValue("custbody_processscrapquantity", context.currentRecord.getValue('custpage_crapquantity'));//废品数量
        // var wocId = woc.save();
        // var lookupFields1 = search.lookupFields({
        //     type: 'workordercompletion',
        //     id: wocId,
        //     columns: ['tranid']
        // });
        // var wocTranid = lookupFields1.tranid;
        // //工序完工回报
        // var count = context.currentRecord.getLineCount("custpage_completedetails");
        // if (count > 0) {
        //     for (var i = 0; i < count; i++) {
        //         var employee = context.currentRecord.getSublistValue("custpage_completedetails", "custpage_employee", i); //员工
        //         //完成数量
        //         var completedCount = context.currentRecord.getSublistValue("custpage_completedetails", "custpage_completedcount", i);
        //         // 新建 工序完工回报
        //         var manuCompleteRec = record.create({type: "customrecord65", isDynamic: true});
        //         manuCompleteRec.setValue("custrecord_workordercompletenumber", wocId);  //完工单号
        //         manuCompleteRec.setValue("custrecord_process", context.currentRecord.getValue('custpage_operationsequence')); //工序
        //         manuCompleteRec.setValue("custrecord_employee", employee); //员工
        //         manuCompleteRec.setValue("custrecord_quantity", completedCount);//数量
        //         manuCompleteRec.setValue("custrecord_workordernumber", woId);   //工单号
        //         manuCompleteRec.save();
        //     }
        // }
        // dialog.alert({title: "提示", message: "创建完工工单成功! " + wocTranid});
        dialog.alert({title: "提示", message: "正在处理,请稍候!"});
        // window.onbeforeunload = function () {
        // };//提交时可以刷新
        return true;
    }

    function validateDelete(context) {
        var quantity = context.currentRecord.getValue('custpage_reportworkquantity');
        var count = context.currentRecord.getLineCount("custpage_completedetails");
        //console.log('count:' + count);
        if (count > 1) {
            var averageQuantity = (quantity / (count - 1)).toFixed(2);
            //console.log('averageQuantity:' + averageQuantity);
            for (var i = 0; i < count; i++) {
                context.currentRecord.selectLine('custpage_completedetails', i);
                context.currentRecord.setCurrentSublistValue('custpage_completedetails', 'custpage_completedcount', averageQuantity);
            }
        }
        return true;
    }

    function validateLine(context) {
        if (context.sublistId === 'custpage_completedetails') {
            var employee = context.currentRecord.getCurrentSublistText(context.sublistId, 'custpage_employee');
            if (!employee) {
                return false;
            } else {
                return true;
            }
        }
    }


    function getSubtractQuantity(operationText, reportworkquantity) {
        var totalPreProcessCompletionQuantity = 0;
        var totalcurrProcessReportQuantity = 0;
        search.create({
            type: 'workordercompletion',
            columns: [],
            filters: [['createdfrom', 'is', woInternalid], 'and', ['mainline', 'is', 'T']]
        }).run().each(function (result) {
            var workordercompletionId = result.id;
            var woc = record.load({
                type: 'workordercompletion',
                id: workordercompletionId,
                isDynamic: true
            });
            if (woc.getText('startoperation') == (parseInt(operationText) - 1)) {//上一道工序
                totalPreProcessCompletionQuantity += parseInt(woc.getValue('completedquantity'));
            } else if (woc.getText('startoperation') == (parseInt(operationText))) { //本道工序
                totalcurrProcessReportQuantity += parseInt(woc.getValue('custbody_reportwork_qty'));
            }
            return true;
        });
        var subtractQuantity = totalPreProcessCompletionQuantity - totalcurrProcessReportQuantity;
        if (reportworkquantity > subtractQuantity) {
            alert('无法报工!\r\n上道工序总完工数量:' + totalPreProcessCompletionQuantity + ',本道工序总报工数量:' + totalcurrProcessReportQuantity);
        }
        return subtractQuantity;
    }


    function clearAll(context) {
        //清空所有字段
        context.currentRecord.setValue('custpage_wo_barcodescan', '');
        context.currentRecord.setValue('custpage_process_barcodescan', '');
        context.currentRecord.setValue('custpage_salesorder', '');
        context.currentRecord.setValue('custpage_wo_num', '');
        context.currentRecord.setValue('custpage_assemblyitem', '');
        context.currentRecord.setValue('custpage_itemname', '');
        context.currentRecord.setValue('custpage_itemsize', '');
        context.currentRecord.setValue('custpage_itemcolor', '');
        context.currentRecord.setValue('custpage_itemcolornumber', '');
        context.currentRecord.setValue('custpage_realperquantity', '');
        context.currentRecord.setValue('custpage_perquantity', '');
        context.currentRecord.setValue('custpage_packagecount', '');
        context.currentRecord.setValue('custpage_packagenumber', '');
        context.currentRecord.setValue('custpage_packagenumberquantity', '');
        context.currentRecord.setValue('custpage_operationname', '');
        context.currentRecord.setValue('custpage_reportworkquantity', '');
        context.currentRecord.setValue('custpage_completedquantity', '');
        context.currentRecord.setValue('custpage_defectivequantity', '');
        context.currentRecord.setValue('custpage_crapquantity', '');

        //清空明细行
        var line = context.currentRecord.getLineCount('custpage_completedetails')
        for (var i = line - 1; i >= 0; i--) {
            context.currentRecord.removeLine('custpage_completedetails', i);
        }


    }


    return {
        pageInit: pageInit,
        validateField: validateField,
        fieldChanged: fieldChanged,
        saveRecord: saveRecord,
        validateLine: validateLine,
        validateDelete: validateDelete,
    };
});

